package com.wdc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wdc.common.Constants;
import com.wdc.controller.dto.UserDto;
import com.wdc.entity.User;
import com.wdc.exception.ServiceException;
import com.wdc.mapper.UserMapper;
import com.wdc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author wdc
 * @since 2024-06-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 登录
     * @param userDto
     * @return
     */
    @Autowired
    private UserMapper userMapper;

    public UserDto login(UserDto userDto) {
      /*  if (userDto.getUsername() == null || userDto.getPassword() == null){
            return false;
        }*/
        User one = getUserInfo(userDto);

        if (one != null){
            BeanUtil.copyProperties(one, userDto,true);
            return userDto;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }


    }

    /**
     * 用户注册
     * @param userDto
     * @return
     */
    public User register(UserDto userDto) {
        User one = getUserInfo(userDto);

        if (one == null){
            one = new User();
            BeanUtil.copyProperties(userDto, one,true);
            save(one);  //copy 完后的数据存储到数据库中
        }else {
            throw new ServiceException(Constants.CODE_600,"用户已经存在");
        }

        return one;
    }


    private User getUserInfo(UserDto userDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDto.getUsername());
        queryWrapper.eq("password", userDto.getPassword());

        User one;
        try {
            one = getOne(queryWrapper);

        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
}
